﻿﻿using DeviceCommons.DeviceMessages.Abstractions;
using DeviceCommons.DeviceMessages.Enums;
using DeviceCommons.DeviceMessages.Models.V1;
using DeviceCommons.Security;
using DeviceCommons.Validation;
using System.Buffers;

namespace DeviceCommons.DeviceMessages.Serialization
{
    public class DeviceMessageSerializer : AbstractMessageSerializer<IDeviceMessage>, IDeviceMessageSerializer
    {
        public DeviceMessageSerializer() : base(new DeviceMessage())
        {
        }

        public override void Serializer(ArrayBufferWriter<byte> writer) => Serializer(writer, Model);

        public override void Serializer(ArrayBufferWriter<byte> writer, IDeviceMessage model)
        {
            IProcessVersion process = model?.Header?.Version switch
            {
                0x01 => new V1.ProcessVersionData(),
                0x02 => new V2.ProcessVersionData(),
                _ => throw new DeviceMessageValidationException(
                    ValidationErrorType.UnsupportedProtocolVersion,
                    $"不支持的协议版本: 0x{model?.Header?.Version:X2}",
                    nameof(model.Header.Version),
                    "0x01 或 0x02",
                    $"0x{model?.Header?.Version:X2}"),
            };

            writer.Write(process.Serializer(model));

            byte[] bytes = writer.WrittenSpan.ToArray();

            if (model.Header?.CRCType != CRCTypeEnum.None)
            {
                writer.Write(CrcCalculator.CalculateCrcBytes(model?.Header?.CRCType ?? CRCTypeEnum.CRC16, writer.WrittenSpan.ToArray()));
            }
        }
    }
}
